/*!
 *  coer环境配置
 *  window.$core
 */
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined'
    ? (module.exports = factory())
    : typeof define === 'function' && define.amd
    ? define(factory)
    : ((global = global || self), (global.$core = factory()));
})(this, function () {
  'use strict';
  let u = {};
  u.ideaName = 'onland'; //项目名称

  // env环境配置
  u.envIndex = 0; //本地环境
  // u.state = 1; //测试环境
  // u.state = 2; //正式环境

  const envObj = {
      local: {
        host: 'http://egg.jokerv.club', //项目host
        apiUrl: '/api/', //api请求拼接地址
        imgHost: '', //图片统一凭借地址
        token: '', //测试默认token
      },
      test: {
        host: '',
        apiUrl: '/api/',
        imgHost: '',
        token: '',
      },
      line: {
        host: '',
        apiUrl: '/api/',
        imgHost: '',
        token: '',
      },
    },
    envIndexArr = ['local', 'test', 'line'];
  u.env = envObj[envIndexArr[u.state]];
  // env环境配置end

  // 缓存操作
  var LS = localStorage;
  u.setLocal = function (key, value) {
    if (value === void 0) {
      value = false;
    }
    key = u.ideaName + '_' + key;
    LS.setItem(
      key,
      typeof value === 'string' ? '0' + value : '1' + JSON.stringify(value)
    );
  };
  u.getLocal = function (key) {
    key = u.ideaName + '_' + key;
    var value = LS.getItem(key);
    return value
      ? value[0] === '1'
        ? JSON.parse(value.substr(1))
        : value.substr(1)
      : undefined;
  };
  u.clearLocal = function (key) {
    if (key === void 0) {
      key = '';
    }
    if (key === '') {
      LS.clear();
    } else {
      LS.removeItem(key);
    }
  };
  // 缓存操作 end
  // 数据操作
  //数组对象固定参数值下标
  u.arrFindIndex = function (arrs, key, value) {
    return arrs.findIndex(function (item) {
      return item[key] === value;
    });
  };
  //数组取集
  u.arr2set = function (arr1, arr2) {
    var _arr1Set = new Set(arr1),
      _arr2Set = new Set(arr2);
    return {
      // 交集
      intersection: function () {
        return arr1.filter(function (item) {
          return _arr2Set.has(item);
        });
      },
      // 并集
      union: function () {
        return Array.from(new Set(__spreadArrays(arr1, arr2)));
      },
      // 补集
      complement: function () {
        return __spreadArrays(
          arr1.filter(function (item) {
            return !_arr2Set.has(item);
          }),
          arr2.filter(function (item) {
            return !_arr1Set.has(item);
          })
        );
      },
      // 差集
      diff: function () {
        return arr1.filter(function (item) {
          return !_arr2Set.has(item);
        });
      },
    };
  };
  u.consoleJSON = function (oldV) {
    //打印JSON方便调试
    console.log(JSON.stringify(oldV));
  };
  u.deepClone = function (cloneObj) {
    //深度克隆
    return JSON.parse(JSON.stringify(cloneObj));
  };
  u.deepMerge = function (Merge1, Merge2) {
    //对象深度合并
    var deepMergeObj = u.deepClone(Merge1);
    for (var key in Merge2) {
      deepMergeObj[key] =
        deepMergeObj[key] &&
        deepMergeObj[key].toString() === '[object Object]' &&
        Merge2[key] &&
        Merge2[key].toString() === '[object Object]'
          ? u.deepMerge(deepMergeObj[key], Merge2[key])
          : (deepMergeObj[key] = Merge2[key]);
    }
    return deepMergeObj;
  };

  u.px2rem = function (pxValue) {
    return pxValue / 37.5;
  };

  u.rem2px = function (remValue) {
    return remValue * u.remSize;
  };
  u.px2rem2px = function (pxValue) {
    return u.rem2px(u.px2rem(pxValue));
  };
  // 数据操作end
  // 规则校验
  //邮箱验证
  u.test = {
    //中文姓名
    name: function (RegValue) {
      return /^[\u4e00-\u9fa5\s·]+$/.test(RegValue);
    },
    //身份证号码
    idCard: function (RegValue) {
      return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(RegValue);
    },
    //手机号
    iphone: function (RegValue) {
      return /^[1][0-9]{10}$/.test(RegValue);
    },
    //邮箱
    email: function (RegValue) {
      return /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/.test(
        RegValue
      );
    },
    //6位验证码
    code: function (RegValue) {
      return /^\d{6}$/.test(RegValue);
    },
  };
  // 规则校验end
  // 拦截器
  u.httpInterceptor = {
    //
    setConfig: null,
    // 请求前的拦截
    request: null,
    // 请求后的拦截
    response: null,
  };

  u.requestUrl = '';
  if (
    window.location.protocol.indexOf('http') &&
    (window.location.host.indexOf('localhost') === -1 ||
      window.location.host.indexOf('127.0.0.1') === -1)
  ) {
    u.requestUrl = window.location.protocol + window.location.host + u.apiUrl;
  } else {
    u.requestUrl = u.host + u.apiUrl;
  }

  u.request = function (url, data = {}, method = 'post', file = false) {
    url = url.indexOf('http') > -1 ? url : u.requestUrl + url; //拼接URL
    if (u.httpInterceptor.request) {
      data = u.httpInterceptor.request(data);
    }
    return new Promise(function (resolve, reject) {
      if (String(window.api) !== 'undefined') {
        window.api.ajax(
          {
            url: url,
            method: method || 'post',
            data: {
              values: data,
              files: {
                file: file,
              },
            },
          },
          function (ret, err) {
            if (ret) {
              if (u.httpInterceptor.response) {
                ret = u.httpInterceptor.response(ret);
              }
              resolve(ret);
            } else {
              reject(err);
              console.log('请求失败');
            }
          }
        );
      } else {
        var xhr_1,
          dataTypeIsObj = Object.prototype.toString.call(data);
        if (window.XMLHttpRequest) {
          xhr_1 = new XMLHttpRequest();
        } else {
          xhr_1 = new ActiveXObject('Microsoft.XMLHTTP');
        }
        switch (dataTypeIsObj) {
          case '[object Object]':
            data = u.urlStringify(data);
            xhr_1.open(method, url + (method === 'get' ? '?' + data : ''));
            xhr_1.setRequestHeader(
              'Content-Type',
              'application/x-www-form-urlencoded'
            );
            break;
          case '[object FormData]':
            xhr_1.open(method, url);
            break;
          default:
        }
        xhr_1.onreadystatechange = function () {
          if (xhr_1.readyState === 4) {
            var ret = JSON.parse(xhr_1.responseText);
            if (xhr_1.status >= 200 && xhr_1.status < 400) {
              if (u.httpInterceptor.response) {
                ret = u.httpInterceptor.response(ret);
              }
              resolve(ret);
            } else {
              reject(ret);
            }
          }
        };
        xhr_1.send(data);
      }
    });
  };

  u.urlStringify = function (urlData) {
    var returnData = '';
    for (var i in urlData) {
      if (urlData[i] || urlData[i] === 0) {
        returnData = returnData
          ? returnData + '&' + i + '=' + urlData[i]
          : returnData + i + '=' + urlData[i];
      }
    }
    return returnData;
  };
  // 请求封装end
  //获取系统判断
  var userAgent = navigator.userAgent;
  u.agentIos = function () {
    //是否是IPhone
    return userAgent.indexOf('iPhone') > -1;
  };
  //获取系统判断end
  //加载外部js
  u.loadJs = function (url, callback) {
    if (callback === void 0) {
      callback = function () {};
    }
    var script = document.createElement('script');
    script.type = 'text/javascript';
    if (typeof callback != 'undefined') {
      if (script.readyState) {
        script.onreadystatechange = function () {
          if (
            script.readyState == 'loaded' ||
            script.readyState == 'complete'
          ) {
            script.onreadystatechange = null;
            callback();
          }
        };
      } else {
        script.onload = function () {
          callback();
        };
      }
    }
    script.src = url;
    document.body.appendChild(script);
  };
  //添加window.onload的方法
  u.addWinLoadEvent = function (func) {
    if (func === void 0) {
      func = function () {};
    }
    if (typeof window.onload != 'function') {
      window.onload = func;
    } else {
      var oldonload = window.onload;
      window.onload = function () {
        oldonload();
        func();
      };
    }
  };
  //加载外部js end
  // 其他
  // 获取url参数得key值
  // interface RegExp {
  //     $1: string;
  //     $2: string;
  //     // etc
  // }

  u.getUrlKey = function (name) {
    return (
      decodeURIComponent(
        (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(
          location.href
        ) || [, ''])[1].replace(/\+/g, '%20')
      ) || null
    );
  };
  //阻止冒泡
  u.stopBubbles = function () {
    // e.stopPropagation()
    window.event ? (window.event.cancelBubble = true) : '';
  };
  u.remSize = 37.5;
  // Flexible 页面适配
  u.setFlexible = function () {
    var clientWidth = document.documentElement.clientWidth,
      clientHeight = document.documentElement.clientHeight,
      docWidth = Math.min(clientWidth, clientHeight),
      docHeight = Math.max(clientWidth, clientHeight),
      rem = docWidth / 10;
    document.documentElement.style.fontSize = rem + 'px';
    u.remSize = rem;
  };

  u.setFlexible();
  window.addEventListener('resize', u.setFlexible);
  window.addEventListener('pageshow', function (e) {
    if (e.persisted) {
      u.setFlexible();
    }
  });

  return u;
});
